package org.javaboy.demo.typeHandler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 这两个注解就表示如果Java代码是 List，数据库是 VARCHAR，就会使用当前这个 TypeHandler
 */
@MappedTypes(List.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class ListVarcharTypeHandler extends BaseTypeHandler<List<String>> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {
//        StringBuffer param = new StringBuffer();
//        for (String s : parameter) {
//            param.append(s)
//                    .append(";");
//        }
        String param = parameter.stream().map(s -> s + ";").collect(Collectors.joining());
        ps.setString(i,param);
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String s = rs.getString(columnName);
//        List<String> list = Arrays.stream(s.split(";")).collect(Collectors.toList());
        if (s!=null) {
            String[] split = s.split(";");
            List<String> list = Arrays.asList(split);
            return list;
        }
        return null;
    }

    @Override
    public List<String> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String s = rs.getString(columnIndex);
//        List<String> list = Arrays.stream(s.split(";")).collect(Collectors.toList());
        if (s!=null) {
            String[] split = s.split(";");
            List<String> list = Arrays.asList(split);
            return list;
        }
        return null;
    }

    @Override
    public List<String> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return null;
    }
}
